package cn.caplike.demo.repository.temp;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

import static com.google.common.collect.Sets.newHashSet;

@SuppressWarnings("ALL")
public class CompleteDemo {
    public static String doPostForm(String httpUrl, Map param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            //connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的(form表单形式的参数实质也是key,value值的拼接，类似于get请求参数的拼接)
            os.write(createLinkString(param).getBytes());
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }

    public static String createLinkString(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        StringBuilder prestr = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr.append(key).append("=").append(value);
            } else {
                prestr.append(key).append("=").append(value).append("&");
            }
        }

        return prestr.toString();
    }

    @SneakyThrows
    public static void main(String[] args) throws InterruptedException {
        final LinkedHashMap<Set<String>, ImmutableMap<String, String>> inputDataMap = buildInputData();

        final List<OutputData> outputDataList = new ArrayList<>();
        inputDataMap.entrySet().forEach(inputData -> {
            final Set<String> phones = inputData.getKey();
            final ImmutableMap<String, String> inputValue = inputData.getValue();

            for (String phone : phones) {
                for (Map.Entry<String, String> inputEntry : inputValue.entrySet()) {
                    phone = StringUtils.trim(phone);
                    final String name = StringUtils.trim(inputEntry.getKey()), idno = StringUtils.trim(inputEntry.getValue());
                    try {
                        String res = exe(ident(name, idno, phone));
                        final String respData = JSONObject.parseObject(res).getString("resp_data");
                        final OutputData outputData = JSON.parseObject(respData, OutputData.class);
                        outputData.setK(phone + "-" + name + "-" + idno);
                        outputDataList.add(outputData);

                        // res = res
                        //     .replace("m12_consume_addr", "近一年消费主要所在地")
                        //     .replace("m1_consume_money", "近1个月消费金额")
                        //     .replace("m3_consume_money", "近3个月消费金额")
                        //     .replace("m12_consume_money", "近12个月消费金额")
                        //     .replace("m1_consume_active", "近1个月消费活跃度")
                        //     .replace("m3_consume_active", "近3个月消费活跃度")
                        //     .replace("m12_consume_active", "近12个月消费活跃度")
                        //     .replace("m12_consume_weekend_money", "近12个月双休日消费金额")
                        //     .replace("m12_consume_night_money", "近12个月午夜消费金额")
                        //     .replace("m12_consume_workday_money", "近12个月工作日消费金额")
                        //     .replace("m12_consume_ze_money", "近12个月整额消费金额")
                        //     .replace("m12_consume_xyk_money", "近12个月信用卡消费金额")
                        //     .replace("m12_consume_weekend_rate", "近12个月双休日消费占比")
                        //     .replace("m12_consume_night_rate", "近12个月午夜消费占比")
                        //     .replace("m12_consume_workday_rate", "近12个月工作日消费占比")
                        //     .replace("m12_consume_ze_rate", "近12个月整额消费占比")
                        //     .replace("m12_consume_xyk_rate", "近12个月信用卡消费占比")
                        //     .replace("m12_consume_maxday_rate", "近12个月最大单日消费占比")
                        //     .replace("m12_consume_fcl_money", "近12个月房产类消费金额")
                        //     .replace("m12_consume_qcl_money", "近12个月汽车类消费金额")
                        //     .replace("m12_consume_jw_money", "近12个月境外消费金额")
                        //     .replace("consume_level", "消费能力综合评级")
                        // ;
                        // System.out.println(inputEntry.getKey() + '-' + inputEntry.getValue() + '-' + phone + ": " + res);
                    } catch (Exception e) {
                        System.err.println(e);
                    }
                }
            }
        });
        final File tempFile = File.createTempFile("2022-08-17", ".xlsx");
        EasyExcel.write(tempFile, OutputData.class).sheet(1).doWrite(outputDataList);
        System.out.println("Done! - " + tempFile.getAbsolutePath());
    }

    // @formatter:off
    @lombok.Data @AllArgsConstructor @NoArgsConstructor
    public static class OutputData {
        @ExcelProperty("K") private String k;
        @ExcelProperty("消费能力综合评级") private String consumeLevel;
        @ExcelProperty("近一年消费主要所在地") private String m12ConsumeAddr;
        @ExcelProperty("近1个月消费金额") private String m1ConsumeMoney;
        @ExcelProperty("近3个月消费金额") private String m3ConsumeMoney;
        @ExcelProperty("近12个月消费金额") private String m12ConsumeMoney;
        @ExcelProperty("近1个月消费活跃度") private String m1ConsumeActive;
        @ExcelProperty("近3个月消费活跃度") private String m3ConsumeActive;
        @ExcelProperty("近12个月消费活跃度") private String m12ConsumeActive;
        @ExcelProperty("近12个月双休日消费金额") private String m12ConsumeWeekendMoney;
        @ExcelProperty("近12个月午夜消费金额") private String m12ConsumeNightMoney;
        @ExcelProperty("近12个月工作日消费金额") private String m12ConsumeWorkdayMoney;
        @ExcelProperty("近12个月整额消费金额") private String m12ConsumeZeMoney;
        @ExcelProperty("近12个月信用卡消费金额") private String m12ConsumeXykMoney;
        @ExcelProperty("近12个月双休日消费占比") private String m12ConsumeWeekendRate;
        @ExcelProperty("近12个月午夜消费占比") private String m12ConsumeNightRate;
        @ExcelProperty("近12个月工作日消费占比") private String m12ConsumeWorkdayRate;
        @ExcelProperty("近12个月整额消费占比") private String m12ConsumeZeRate;
        @ExcelProperty("近12个月信用卡消费占比") private String m12ConsumeXykRate;
        @ExcelProperty("近12个月最大单日消费占比") private String m12ConsumeMaxdayRate;
        @ExcelProperty("近12个月房产类消费金额") private String m12ConsumeFclMoney;
        @ExcelProperty("近12个月汽车类消费金额") private String m12ConsumeQclMoney;
        @ExcelProperty("近12个月境外消费金额") private String m12ConsumeJwMoney;
    }
    // @formatter:on

    private static String exe(TreeMap customData) throws Exception {
        final String companyId = "08200063554306985162983347810587"; /*"d6518f1e-9270-11e9-890c-9801a79f5a77";*/
        final String url = "https://guard.shouxin168.com/api/lightning/product/query"; /*"http://sandbox.shouxin168.net/api/lightning/product/query";*/
        final String key = "nVzLXizOJzh1e9GF"; /*"Q0ymUIe1t26ZfG7s";*/

        // customData.put("name", "");
        // customData.put("bank_card", "");
        // customData.put("ident_number", "");
        // customData.put("service", "bankcard_triple_elements_alpha_service");
        // customData.put("mode", "bankcard_triple_elements_alpha_mode");

        // RSA 加密
        final String js = RSA.getSignContent(new JSONObject(customData));
        final String signVal = RSA.sign(js, RSA.PRIVATE_KEY);

        // System.out.println(signVal);

        // AES 加密
        final String bizDataRaw = JSONObject.toJSON(customData).toString();

        // System.out.println("AES 加密模型是：");

        final String bizDataEncoded = AES.encrypt(bizDataRaw, key);

        // System.out.println(bizDataEncoded);
        // System.out.println("原始数据是：");
        // System.out.println(AES.decrypt(AES.encrypt(bizDataRaw, key), key));

        final Map<String, Object> data = new HashMap<>();
        final String signEncoded = URLEncoder.encode(signVal);
        final String bizDataEncoded2 = URLEncoder.encode(bizDataEncoded);
        data.put("institution_id", companyId);
        data.put("biz_data", bizDataEncoded2);
        data.put("sign", signEncoded);

        return doPostForm(url, data);
    }

    static TreeMap ident(String name, String ident_number, String phone) {
        final TreeMap<Object, Object> map = new TreeMap<>();
        map.put("encryption", "plaintext");
        map.put("service", "personal_consume_merchant_service");
        map.put("mode", "mode_personal_consume_merchant");
        map.put("name", name);
        map.put("ident_number", ident_number);
        map.put("phone", phone);
        return map;
    }

    static LinkedHashMap<Set<String>, ImmutableMap<String, String>> buildInputData() {
        final LinkedHashMap<Set<String>, ImmutableMap<String, String>> map = new LinkedHashMap<>();

        map.put(newHashSet("18403628881"), ImmutableMap.<String, String>builder().put("饶静侠", " 342201196309011846 ").build());
        map.put(newHashSet("18403628882"), ImmutableMap.<String, String>builder().put("张安娜", " 340103195903173048 ").build());
        map.put(newHashSet("18403628883"), ImmutableMap.<String, String>builder().put("杨志清", " 342201196311010439 ").build());
        map.put(newHashSet("18403628884"), ImmutableMap.<String, String>builder().put("张惠兰", " 342301195512020626 ").build());
        map.put(newHashSet("18403628885"), ImmutableMap.<String, String>builder().put("王先华", " 340321196111106881 ").build());
        map.put(newHashSet("18403628886"), ImmutableMap.<String, String>builder().put("刘开侠", " 34032119621102690X ").build());
        map.put(newHashSet("18403628887"), ImmutableMap.<String, String>builder().put("刘英 ", " 340321196203226880 ").build());
        map.put(newHashSet("18403628888"), ImmutableMap.<String, String>builder().put("杨琨 ", " 340121196310109136 ").build());
        map.put(newHashSet("18403628889"), ImmutableMap.<String, String>builder().put("张敏兰", " 34012119621210004X ").build());
        map.put(newHashSet("18403628880"), ImmutableMap.<String, String>builder().put("蔡学工", " 340103195903161012 ").build());
        map.put(newHashSet("18403628811"), ImmutableMap.<String, String>builder().put("张安丽", " 340103196201293023 ").build());
        map.put(newHashSet("18403628821"), ImmutableMap.<String, String>builder().put("周玉萍", " 34012119800210552X ").build());
        map.put(newHashSet("18403628831"), ImmutableMap.<String, String>builder().put("高伟 ", " 340604198310170420 ").build());
        map.put(newHashSet("18403628841"), ImmutableMap.<String, String>builder().put("高凤云", " 340604197902210428 ").build());
        map.put(newHashSet("18403628851"), ImmutableMap.<String, String>builder().put("姚灯灵", " 342101197606031324 ").build());
        map.put(newHashSet("18403628861"), ImmutableMap.<String, String>builder().put("张桂芳", " 342421196412246025 ").build());
        map.put(newHashSet("18403628871"), ImmutableMap.<String, String>builder().put("牛敏 ", " 34122719850520564X ").build());
        map.put(newHashSet("18403628881"), ImmutableMap.<String, String>builder().put("高立国", " 340604195311170437 ").build());
        map.put(newHashSet("18403628891"), ImmutableMap.<String, String>builder().put("韩卫卫", " 341227198401180046 ").build());
        map.put(newHashSet("18403628801"), ImmutableMap.<String, String>builder().put("韩文平", " 342130195306250018 ").build());
        map.put(newHashSet("18403628181"), ImmutableMap.<String, String>builder().put("吴传芳", " 340102196201050527 ").build());
        map.put(newHashSet("18403628281"), ImmutableMap.<String, String>builder().put("余保仁", " 340121195902053119 ").build());
        map.put(newHashSet("18403628381"), ImmutableMap.<String, String>builder().put("金全华", " 340104196308240569 ").build());
        map.put(newHashSet("18403628481"), ImmutableMap.<String, String>builder().put("束维林", " 340104197101060522 ").build());
        map.put(newHashSet("18403628581"), ImmutableMap.<String, String>builder().put("吴翔 ", " 340311199004020215 ").build());
        map.put(newHashSet("18403628681"), ImmutableMap.<String, String>builder().put("李叶 ", " 340321199306139302 ").build());
        map.put(newHashSet("18403621881"), ImmutableMap.<String, String>builder().put("金德凤", " 340123196501178225 ").build());
        map.put(newHashSet("18403611881"), ImmutableMap.<String, String>builder().put("赵中菊", " 34242519630311204X ").build());
        map.put(newHashSet("18403611281"), ImmutableMap.<String, String>builder().put("董永珍", " 341202196008100242 ").build());
        map.put(newHashSet("18403611231"), ImmutableMap.<String, String>builder().put("赵从荟", " 340123196704180325 ").build());
        map.put(newHashSet("18403510234"), ImmutableMap.<String, String>builder().put("沈平 ", " 34242519631018202X ").build());
        map.put(newHashSet("18403501234"), ImmutableMap.<String, String>builder().put("钱荣霞", " 340102196110074021 ").build());
        map.put(newHashSet("18403511034"), ImmutableMap.<String, String>builder().put("高国霞", " 340111195908270023 ").build());
        map.put(newHashSet("18403511214"), ImmutableMap.<String, String>builder().put("韦道友", " 340111195702280533 ").build());
        map.put(newHashSet("18403511224"), ImmutableMap.<String, String>builder().put("钱惠霞", " 340102195811193029 ").build());
        map.put(newHashSet("18403511234"), ImmutableMap.<String, String>builder().put("韩新鸣", " 340102195802073527 ").build());
        map.put(newHashSet("18403511235"), ImmutableMap.<String, String>builder().put("罗永珍", " 340102196310263046 ").build());
        map.put(newHashSet("18403511233"), ImmutableMap.<String, String>builder().put("周玲珍", " 340102195712313523 ").build());
        map.put(newHashSet("18403511239"), ImmutableMap.<String, String>builder().put("王明元", " 340102196312312534 ").build());
        map.put(newHashSet("18403531234"), ImmutableMap.<String, String>builder().put("周丽霞", " 232602197303310025 ").build());
        map.put(newHashSet("18403514234"), ImmutableMap.<String, String>builder().put("李娜 ", " 340824199607182423 ").build());
        map.put(newHashSet("18403515234"), ImmutableMap.<String, String>builder().put("吴再望", " 340881198512245316 ").build());
        map.put(newHashSet("18403516234"), ImmutableMap.<String, String>builder().put("张昌月", " 340102196507263023 ").build());
        map.put(newHashSet("18403517234"), ImmutableMap.<String, String>builder().put("王静 ", " 340111197009287525 ").build());
        map.put(newHashSet("18508511234"), ImmutableMap.<String, String>builder().put("张丽萍", " 340111197009027520 ").build());
        map.put(newHashSet("18409511234"), ImmutableMap.<String, String>builder().put("张庆云", " 340111196205277522 ").build());
        map.put(newHashSet("18400511234"), ImmutableMap.<String, String>builder().put("施福虎", " 340102196406063030 ").build());
        map.put(newHashSet("18422511234"), ImmutableMap.<String, String>builder().put("顾惠娟", " 340102196609183024 ").build());
        map.put(newHashSet("18444511234"), ImmutableMap.<String, String>builder().put("王照富", " 340111195904217516 ").build());

        return map;
    }
}